using System.Diagnostics;
using System.Text;
using NetChinese.Interfaces;

namespace NetChinese.Services
{
    /// <summary>
    /// 命令行执行器
    /// </summary>
    public class CommandLineExecutor : ICommandExecutor
    {
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="command">要执行的命令</param>
        /// <param name="showOutput">是否显示命令输出，默认为true</param>
        /// <returns>命令执行是否成功</returns>
        public async Task<bool> ExecuteCommandAsync(string command, bool showOutput = true)
        {
            try
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = $"/c chcp 65001 > nul && {command}",
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        CreateNoWindow = true,
                        StandardOutputEncoding = Encoding.UTF8,
                        StandardErrorEncoding = Encoding.UTF8
                    }
                };
                
                process.Start();
                
                while (!process.HasExited)
                {
                    string output = await process.StandardOutput.ReadLineAsync();
                    if (!string.IsNullOrEmpty(output) && showOutput)
                        Console.WriteLine(output);
                }
                
                if (process.ExitCode != 0)
                {
                    string error = await process.StandardError.ReadToEndAsync();
                    if (showOutput)
                    {
                        throw new Exception($"命令执行失败: {error}");
                    }
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                if (showOutput)
                {
                    Console.WriteLine($"执行命令时出错: {ex.Message}");
                }
                return false;
            }
        }
    }
} 